package name.huzhenbo.java.threads;

import java.util.HashMap;
import java.util.Map;

/**
 * This is a simple implementation of ThreadLocal.
 */
class SimpleThreadLocal<T> {
    private Map<Thread, T> map = new HashMap<Thread, T>();

    public T get() {
        T t = map.get(Thread.currentThread());
        if (t == null && !map.containsKey(Thread.currentThread())) {
            map.put(Thread.currentThread(), initialValue());
        }
        return map.get(Thread.currentThread());
    }

    public void set(T t) {
        map.put(Thread.currentThread(), t);
    }

    protected T initialValue() {
        return null;
    }

    public void remove() {
        map.remove(Thread.currentThread());
    }

}
